<template>
  <view>
    <!-- 日期选择 -->
    <lxCalendar @change="change" @date_choose="date_choose" @week_time="week_time" @getTimes="getTimes" style="background: #fff;"></lxCalendar>

    <!-- 日表 -->
    <day-table v-if="!selected" scrollHeight="height:calc(100vh)" :chooseDate="chooseDate" :meetingList="meetingList"
      :unitHeight="unitHeight" :unitMinute="unitMinute" :showMinute="showMinute" :defaultChoose="defaultChoose" :scale="scale"
      :minRatio="minRatio" :minAll="minAll" :defaultList="defaultList" :nowLine="nowLine" :scrollTop="scrollTop"
      :timeId="timeId" :isToday="isToday" :meetingDetail="meetingDetail" @showDetail="showDetail" @isTodayFun="isTodayFun"
      @createMeeting="createMeeting" @scroll="scroll"></day-table>

    <!-- 周表 -->
    <week-table v-show="selected" :week_defaultList="week_defaultList" scrollHeight="height:calc(100vh)" :chooseDate="chooseDate"
      :meetingList="meetingList" :unitHeight="unitHeight" :unitMinute="unitMinute" :showMinute="showMinute"
      :defaultChoose="defaultChoose" :scale="scale" :minRatio="minRatio" :minAll="minAll" :nowLine="nowLine" :scrollTop="scrollTop"
      :timeId="timeId" :isToday="isToday" :meetingDetail="meetingDetail" @showDetail="showDetail" @isTodayFun="isTodayFun"
      @createMeeting="createMeeting" @scroll="scroll"></week-table>

    <!-- 销客码显示区 -->
    <view class="cu-modal" :class="modalName=='Image'?'show':''" @click.stop="hideModal">
      <view class="cu-dialog">
        <view class="bg-img" style="height:400px;">
          <image :src="bg_qrcode" mode="widthFix" style="top: 50%;left: 50%;transform: translate(-50%, -50%);position: absolute;width: 300px;"></image>
          <view class="cu-bar justify-end text-white">
            <view class="action">
              <text class="cuIcon-close "></text>
            </view>
          </view>
        </view>

      </view>
    </view>

    <canvas canvas-id="qrcode" style="width: 600px;height: 600px;position: fixed;top: 9999999rpx;left: 1000rpx;" />
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  let timeOutEvent = 0;
  let scrollYtop = 0;
  let hidID = -1;

  function vibrate() {
    uni.vibrateShort();
  };
  import lxCalendar from '@/components/lx-calendar/lx-calendar.vue';

  import dayTable from "@/components/dayTable/dayTable.vue";
  import weekTable from "@/components/weekTable/weekTable.vue";

  import uQRCode from '@/js_sdk/Sansnn-uQRCode/uqrcode.js'
  export default {
    components: {
      lxCalendar,
      dayTable,
      weekTable
    },
    data() {
      return {
        openid: '',
        unitHeight: 16,
        unitMinute: 15,

        // 日表
        chooseDate: '',
        modalName: null,
        showMinute: 60,
        defaultChoose: 8,
        scale: 0,
        minRatio: 0,
        minAll: 0,
        defaultList: [],
        meetingList: [], // 上课列表
        nowLine: "",
        startId: 0,
        isCreate: false,
        createMeet: "",
        nowTime: {},
        scrollTop: 0,
        timeId: -1,
        isToday: 0,
        meetingDetail: "",

        // 周表
        week_defaultList: [],
        startTime: '',


        bg_qrcode: '', // 二维码图片
        uQRCode: '', // 二维码信息
        selected: false, // 默认 false 显示日表
      };
    },
    created() {
      var that = this

      this.unitHeight = 16; // 16px
      this.defaultChoose = parseInt(this.defaultChooseLong / 15) || 8; // 120分钟
      this.minMute = parseInt(this.showMin) || 1;

      this.minRatio = this.showMinute / this.unitMinute; // 4
      this.minAll = 1440 / this.unitMinute; // 96

      this.scrollTop = this.unitHeight * 36;
      //后续修改
      this.getDefaultTable(); // 日表
      // this.getWeek_defaultList(); // 周表
      this.getMeetingList();
      this.isTodayFun(this.chooseDate)

      // 初始化选中 日表
      let day_ = new Date();
      let day_now = day_.getFullYear() + '-' + this.p((day_.getMonth() + 1)) + '-' + this.p(day_.getDate())
      uni.getStorage({
        key: 'openid',
        success: (res) => {
          that.openid = res.data
          this.getdaycourse(day_now)
        },
        fail: () => {}
      });

    },
    onReady() {
      let that = this;
      uni.getStorage({
        key: 'openid',
        success: (res) => {
          that.openid = res.data
        },
        fail: () => {}
      });
    },
    methods: {
      getTimes(e) {
        this.chooseDate = e
      },
      week_time(start, end) {
        console.log('111111111111111', start, end)
      },
      date_choose(selected) {
        this.selected = selected
        if (this.selected) { // 显示周表
          this.getWeek_defaultList();
        }
      },
      async getdaycourse(time) {
        var data = {
          'coachId': this.openid, // 显示日表
          'startTime': this.chooseDate,
          'endTime': this.chooseDate,
        }

        let res = await this.$myRuquest({
          url: '/coach/course/getReservationListByCoachId',
          data,
        })
        console.log('查看日表数据', res)
        if (res.data.result == 200) {
          this.meetingList = res.data.datas
          this.getMeetingList()
        } else {
          uni.showToast({
            title: res.data.msg
          })
        }
      },
      change(e) {
        if (this.selected) { // 显示周表
          let str2 = Date.parse(e.fulldate);
          var now = new Date(str2); // Tue Nov 03 2020 15:30:00 GMT+0800 (中国标准时间)
          var nowTime = now.getTime(); // 1604388600357
          var day = now.getDay(); // 2  // 礼拜二, 0, 1, 2
          var oneDayTime = 24 * 60 * 60 * 1000;
          // 显示 上 周日
          var Sunday = nowTime - (day) * oneDayTime;
          // 显示 本 周六
          var Saturday = nowTime + (6 - day) * oneDayTime;
          // 初始化日期时间
          var sunday = new Date(Sunday);
          var start = sunday.getFullYear() + '-' + this.p((sunday.getMonth() + 1)) + '-' + this.p(sunday.getDate())
          var saturday = new Date(Saturday);
          var end = saturday.getFullYear() + '-' + this.p((saturday.getMonth() + 1)) + '-' + this.p(saturday.getDate())
          // 打印查看结果
          console.log('startTime...', start)
          console.log('end...', end)
        } else {
          this.chooseDate = e.fulldate
          console.log('33333333333333333', this.chooseDate)
          this.getdaycourse(e.fulldate)
        }


      },
      p(s) {
        return s < 10 ? '0' + s : s
      },
      //点击时间列表 弹出销客弹窗
      showDetail(item, index) {
        console.log('查看详情', item)
        uni.setStorageSync('yuyue', item)
        uni.navigateTo({
          url: '../../pagesA/customer_details/customer_dynamic?id='+item.userId
        })
        // this.uQRCode = 'https://jxjssservice.jxfit.cn?courseId=' + item.courseId + '&rId=' + item.rId + '&coachId=' +
        //   this.openid
        // this.modalName = 'Image'
        // this.make()
      },
      async make() {
        var that = this
        // 回调方式
        uQRCode.make({
          canvasId: 'qrcode',
          componentInstance: this,
          text: that.uQRCode,
          size: 200,
          margin: 10,
          backgroundColor: '#ffffff',
          foregroundColor: '#000000',
          fileType: 'jpg',
          correctLevel: uQRCode.errorCorrectLevel.H,
          success: res => {}
        })

        // Promise
        uQRCode.make({
          canvasId: 'qrcode',
          componentInstance: this,
          text: that.uQRCode,
          size: 400,
          margin: 10,
          backgroundColor: '#ffffff',
          foregroundColor: '#000000',
          fileType: 'jpg',
          correctLevel: uQRCode.errorCorrectLevel.H
        }).then(res => {})

        // 同步等待
        var res = await uQRCode.make({
          canvasId: 'qrcode',
          componentInstance: this,
          text: that.uQRCode,
          size: 400,
          margin: 10,
          backgroundColor: '#ffffff',
          foregroundColor: '#000000',
          fileType: 'jpg',
          correctLevel: uQRCode.errorCorrectLevel.H
        })
        this.bg_qrcode = res
      },
      createMeeting() {
        let self = this;
        let id = parseInt(this.startId);
        let top = "",
          stId = 0,
          endId = 0,
          height = "";
        let startTime = "";
        let endTime = "";
        if (id < 2) {
          id = 2;
        } else if (id > 89) {
          // endId = 96;
          id = 90;
          stId = 88;
        } else {
          stId = id - 2;
          // endId = id + 6;
        };

        //当前建会判断；
        if (this.isToday === 0) {
          let isOld = this.isOldtime(stId, id);
          if (isOld === -1) {
            this.showError("过去时间不可预订");
            timeOutEvent = 1;
            return;
          } else if (isOld > 0) {
            stId = isOld;
            id = stId + 2;
          }
        }
        endId = stId + this.defaultChoose;
        let test = this.defaultChoose - 1.9;
        this.meetingList.forEach(function(item) {
          if (id - item.endId < 2.1 && id - item.endId > -0.1) {
            stId = item.endId;
          }
          // if (item.startId - id < 6.1 && item.startId - id > -0.1) {
          //   endId = item.startId;
          // }
          if (item.startId - id < test && item.startId - id > -0.1) {
            endId = item.startId;
          }

        });
        top = (stId * self.unitHeight);
        startTime = self.defaultList[stId].timeTitle;
        endTime = self.defaultList[endId].timeTitle;
        height = self.unitHeight * (endId - stId);
        let startTimeShow = startTime,
          endTimeShow = endTime;

        if (!!self.isHidTime(stId) && self.isToday == 0) {
          startTimeShow = '';
        };

        let meeting = {
          isFlex: '',
          trueStyle: 'top:0;height:' + height + "px;",
          style: 'top:' + top + 'px;height:' + height + "px;",
          meetingName: '再次点击新建日程',
          time: startTime + ' - ' + endTime,
          length: endId - stId,
          idSt: stId,
          idEnd: endId,
          height: height,
          top: top,
          startTime: startTime,
          endTime: endTime,
          startTimeShow: startTimeShow,
          endTimeShow: endTimeShow
        };
        this.isCreate = true;
        this.createMeet = meeting;
        this.startTop = top;
      },
      //是否隐藏时间
      isHidTime(id) {
        let timeId = this.timeId;
        if (id == timeId || id == timeId + 1) {
          return true;
        } else {
          return false;
        }
      },
      //判断是否为过去时间
      isOldtime(startId, touchid) {
        let nowDate = new Date();
        let timeNowId = nowDate.getHours() * 4 + Math.ceil(nowDate.getMinutes() / 15);
        if (touchid < timeNowId) {
          return -1; //过去时间不能预定
        } else {
          if (startId < timeNowId) {
            return timeNowId; //开始时间为timeNowId
          }
          return 0; //开始时间不变
        };
      },
      // 手机端区别手指滚动和点击操作
      scroll(e) {
        // 手机端区别手指滚动和点击操作
        clearTimeout(timeOutEvent);
        scrollYtop = e.detail.scrollTop;
      },
      hideModal(e) {
        this.modalName = null
        this.getdaycourse();
        
      },
      isTodayFun(d) {
        let isToday;
        let td = new Date();
        td = new Date(td.getFullYear(), td.getMonth(), td.getDate());
        let od = new Date(d);
        od = new Date(od.getFullYear(), od.getMonth(), od.getDate());
        let xc = od - td;
        let result = "";
        if (xc < 0) {
          isToday = -1
        } else if (xc == 0) {
          isToday = 0;
        } else {
          isToday = 1;
        }
        this.isToday = isToday;
        // if (this.isToday == 0) {
        //   this.getTimeNow();
        // }
      },

      // 获取 日 健身时间列表数据 并处理
      getMeetingList() {
        let meetingList = this.meetingList
        let list = [];
        for (let i = 0; i < meetingList.length; i++) {
          let start = meetingList[i].startTime.substring(11, 16).split(":");
          let end = meetingList[i].endTime.substring(11, 16).split(":");

          let st = parseInt(start[0] * this.minRatio) + parseInt(start[1] / this.unitMinute);
          let ed = parseInt(end[0] * this.minRatio) + parseInt(end[1] / this.unitMinute);

          let height = "height:" + ((ed - st) * this.unitHeight) + "px;";
          let top = "top:" + ((st * this.unitHeight)) + "px;";
          let isFlex = "";
          let bgClass = "blurBg"
          // if ((ed - st) < 2) {
          //   isFlex = "isFlex "
          // }
          if (!meetingList[i].isMe) {
            bgClass = 'redBg '
          }

          list.push({
            top: st * this.unitHeight,
            style: height + top,
            userName: meetingList[i].userName,
            rId: meetingList[i].rId,
            userId: meetingList[i].userId,
            courseId: meetingList[i].courseId,
            time: meetingList[i].startTime.substring(5, 16) + '-' + meetingList[i].endTime.substring(11, 16),
            isFlex: isFlex,
            startId: st,
            endId: ed,
            bgClass: bgClass
          })
        }
        this.meetingList = list;
        // console.log('日程')
        // console.log(this.meetingList)
      },
      // 日表 面板
      getDefaultTable() {
        let self = this;
        let list = [],
          // all = self.minAll,
          rat = this.minRatio;
        for (let i = 0; i < 97; i++) {
          let time = "",
            timeClass = "";
          let hour = Math.floor(i / rat);
          hour = hour < 10 ? '0' + hour : hour;

          if (i % rat === 0) {
            time = hour + ":00";
            timeClass = "hasTime"
          } else {
            time = hour + ':' + i % rat * self.unitMinute;
          }
          list.push({
            trClass: timeClass,
            timeTitle: time,
          })
        };
        this.defaultList = list;
        console.log(this.defaultList)
      },
      // 周表格 面板
      getWeek_defaultList() {
        let self = this;
        let list = [],
          // all = self.minAll,
          rat = this.minRatio;
        for (let i = 0; i < 97; i++) {
          let time = "",
            timeClass = "";
          let hour = Math.floor(i / rat);
          hour = hour < 10 ? '0' + hour : hour;

          if (i % rat === 0) {
            time = hour + ":00";
            timeClass = "hasTime"
          } else {
            time = hour + ':' + i % rat * self.unitMinute;
          }
          list.push({
            trClass: timeClass,
            timeTitle: time,
          })
        };
        this.week_defaultList = list;
        // console.log(this.week_defaultList)
      },

    }
  }
</script>

<style>
  .canvas-hide {
    /* 1 */
    position: fixed;
    right: 100vw;
    bottom: 100vh;
    /* 2 */
    z-index: -9999;
    /* 3 */
    opacity: 0;
  }
</style>
